$(function() {
    var form = layui.form;

    // 初始化富文本
    initEditor();

    // 获取分类，并渲染出来
    $.ajax({
        url: "/my/article/cates",
        success: function(res) {
            if (res.status === 0) {
                $('select[name="cate_id"]').html(template("tpl-category", res));
                form.render("select");
            }
        },
    });

    // 显示默认的裁切效果
    var $image = $("#image");
    var options = {
        aspecRatio: 400 / 280,
        preview: ".img-preview",
    };
    $image.cropper(options);

    $("#chooseImage").click(function() {
        $("#file").click();
    });

    // 文件域的内容改变时，重置剪裁区
    $("#file").change(function() {
        var url = URL.createObjectURL(this.files[0]);
        // 销毁裁剪区，更改链接，重建裁剪区
        $image.cropper("destroy").attr("src", url).cropper(options);
    });

    var state = "";
    $("#fabu").click(function() {
        state = "已发布";
    });
    $("#caogao").click(function() {
        state = "草稿";
    });

    $("form").on("submit", function(e) {
        e.preventDefault();
        var data = new FormData(this);
        data.append("state", state);

        $image
            .cropper("getCroppedCanvas", {
                width: 400,
                height: 280,
            })
            .toBlob(function(blob) {
                data.append("cover_img", blob);
                $.ajax({
                    type: "post",
                    url: "/my/article/add",
                    data: data,
                    success: function(res) {
                        layer.msg(res.message);
                        if (res.status === 0) {
                            location.href = "/article/article.html";
                        }
                    },
                    processData: false,
                    contentType: false,
                });
            });
    });
});